package com.snk.common.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class SysCacheAspect {

    //假设此对象为存储数据的一个缓存对象
    private Map<String,Object> cache=new ConcurrentHashMap<>();//线程安全的hashMap



    /**
     * 注解方式的切入点表达式的定义（细粒度的表达式）
     */
    @Pointcut("@annotation(com.snk.common.annotation.RequiredCache)")
    public void doCache(){}

    @Pointcut("@annotation(com.snk.common.annotation.ClearCache)")
    public void doClearCache(){}

    /**
     * 扩展业务
     * @param jp
     * @return
     * @throws Throwable
     */
    @Around("doCache()")
    public Object doAround(ProceedingJoinPoint jp)
        throws Throwable{
        System.out.println("GET data from cache");
        Object obj=cache.get("DEPT key");//这里的DEPTkey目前为一个固定值
        if (obj!=null)return obj;
        obj=jp.proceed();
        System.out.println("Put data to cache");
        cache.put("DEPT key", obj);
        return obj;
    }

    @AfterReturning("doClearCache()")
    public void doAfterReturning(){
        cache.remove("DEPT key");
        System.out.println("OK");
    }

}
